import Header from "./../../components/Header";
import {Row, Col} from "./../../rsuite";
import {Link} from "react-router";
import {connect} from "react-redux";
import NoData from "./../../components/nodata";
import Search from "./../../components/search";
import Panel from "./../../elements/Panel";
import Pagination from "./../../components/Pagination/cpage";
import Loading from "./../../components/loading/";
import {Config, Lang, Fetch} from "./../../libs/";
import {SUBJECT, PAGE_SUBJECT} from "./../../actions/subject";
import {URL, pureUrl, md5Url} from "./../../libs/Url";
import {
    fetch,
    fetchUser,
    fetch_remove,
    enable_delete_btn,
    setArgumentItem,
    selectAllItem,
    selectItem
} from "../../actions";
import Animate from 'rc-animate';
import DownDrop from "./../../components/category";


const Activity = React.createClass({
    getInitialState(){
        return {
            enable_batch_delete_num: 0,//可批量删除的选中项
            setting: {},// page settings
            query: {}, categories: [], list: [],
            loaded: false,
        }
    },
    componentDidMount() {
        const {dispatch} = this.props, self = this;
        dispatch(fetchUser());
        Promise.all([
            Fetch(URL.HOMEWORK_FIND)
        ])
            .then(res=> {
                self.setState({
                    list: res[0].list,
                    page: res[0].cpage,
                    loaded: true,
                    enable_batch_delete_num: 0
                })

            })
            .catch(e=> {
                console.log(e)
            })
    },
    search(obj){
        const self = this;
        // self.setState({
        //     loaded: false
        // });
        Fetch(URL.HOMEWORK_FIND, {body: Object.assign(this.state.query, obj || {})})
            .then(res=> {
                console.log(res);
                self.setState({
                    query: Object.assign(self.state.query || {}, obj || {}),
                    list: res.list,
                    loaded: true,
                    page: res.cpage,
                })
            })
            .catch(e=> {
                console.log(e);
            })
    },
    handleSelect(eventKey){
        const {dispatch} = this.props;
        dispatch(fetch({type: eventKey, url: URL.TEACH_SCHEDULE_FIND}))
    },
    deleteItem(ids){
        let self = this;
        Fetch(URL.HOMEWORK_DELETE, {body: {ids: ids}})
            .then(res=> {
                alert('成功');
                var filter = _.filter(self.state.list, function (item) {
                    if (!ids) {
                        return !item.checked;
                    } else {
                        return ids.indexOf(item.id) == -1;
                    }
                });
                self.setState({
                    list: filter,
                    page: Object.assign(self.state.page, {
                        total: self.state.page.total - ids.split(',').length
                    }),
                    enable_batch_delete_num: self.state.enable_batch_delete_num - ids.split(',').length
                })
            })
            .catch(e=> {
                alert('Fail');
                console.log(e)
            })
    },
    isLoading(){

    },
    selectedItem(index, item){
        let self = this;
        self.setState({
            enable_batch_delete_num: item.checked ? (self.state.enable_batch_delete_num + 1) : ((self.state.enable_batch_delete_num - 1)),
            list: [
                ...self.state.list.slice(0, index),
                Object.assign(self.state.list[index], item || {}),
                ...self.state.list.slice(index + 1)
            ],
        })
    },
    selectedItemAll(checked){
        let self = this,
            {user} = this.props,
            num = 0;

        var list = self.state.list.map(item=> {
            item.checked = checked ? true : false;
            if (item.checked)num++;
            return item;
        });
        this.setState({
            list: list,
            enable_batch_delete_num: checked ? num : 0
        })
    },
    render(){
        const self = this;
        const {dispatch, user} = this.props;
        let data = {list: this.state.list || [], filter_category: this.state.categories || []},
            state = this.state;
        let argument = {
            //  state: label,
            label_class: ''
        };
        return (
            <Panel>
                <Header>发布作业 </Header>
                <Animate
                    component=""
                    transitionName="fade"
                >
                    {state.loaded ? null : <Loading />}
                </Animate>

                <div className="row table-list-head">
                    <Col xs={6} md={6}>
                        <Link className='btn btn-primary btn-sm' to={Config.MENUS_ABSOLUTE.HOMEWORK_ADD}>
                            <i className="fa fa-plus"></i> {Lang.ACTIVITY_LIST.create}
                        </Link>
                        <button disabled={state.enable_batch_delete_num == 0}
                                onClick={(e)=> {
                                    if (confirm(Lang.ACTIVITY_LIST.delete_confirm)) {
                                        self.deleteItem(_.pluck(_.filter(data.list, (item)=> {
                                            return item.checked;
                                        }), 'id').join(','));
                                    }
                                }}
                                className="btn btn-default btn-sm"
                        >{Lang.ACTIVITY_LIST.delete}
                        </button>
                    </Col>
                    <Col xs={6} md={3} mdOffset={3}>
                        <Search submit={(value)=> {
                            this.search({keyword: value});
                        }}/>
                    </Col>
                </div>
                <Row>
                    <Col xs={12} md={12}>
                        <table
                            className="table table-bordered table-striped general-table">
                            <thead>
                            <tr>
                                <th style={{width: '50px'}}>

                                    <input
                                        type="checkbox"
                                        onClick={(e)=> {
                                            this.selectedItemAll(e.target.checked);
                                        }}/>
                                </th>
                                <th style={{width: '60px'}}>NO.</th>
                                <th>{Lang.homework.header.subject}</th>
                                <th>
                                    {Lang.homework.header.detail}
                                </th>
                                <th style={{width:113}}>
                                    <DownDrop
                                        label={state.label_class || Lang.homework.header.grade }>
                                        {user.user['class'].map((item, index)=> {
                                            return <li key={index}>
                                                <a href="javascript:void(0);"
                                                   onClick={()=> {
                                                       self.search({
                                                           classid: item.classid
                                                       });
                                                       self.setState({
                                                           label_class:item['class'].name,
                                                       })
                                                   }}>{item['class'].name}</a>
                                            </li>
                                        })}
                                    </DownDrop>
                                </th>
                                <th >{Lang.homework.header.time}</th>
                                <th style={{width: '120px'}}>{Lang.ACTIVITY_LIST.header.oper}</th>
                            </tr>
                            </thead>
                            <tbody>
                            {
                                data.list.map((item, index)=> {
                                        item.index = index;
                                        return <tr key={index}>
                                            <td>
                                                <input type="checkbox" checked={(item.checked ? 'checked' : '')}
                                                       onClick={(e)=> {
                                                           self.selectedItem(index, {checked: !item.checked})
                                                       } }/>
                                            </td>
                                            <td className="hidden-phone">{index + 1}</td>
                                            <td>{item['subject'] && item['subject'].name}</td>
                                            <td><Link to={
                                                Config.MENUS_ABSOLUTE.HOMEWORK_DETAIL.replace(':id', item.id)
                                            }>{item.comment} {
                                                item.fileids ? <i className="fa fa-paperclip"></i> : ''
                                            }</Link></td>
                                            <td>{item['class'] && item['class'].name}</td>
                                            <td>{Moment(item.intime).format('YYYY-MM-DD HH:mm:SS')}</td>
                                            <td>
                                                <Link
                                                    to={Config.MENUS_ABSOLUTE.HOMEWORK_DETAIL.replace(':id', item.id)}
                                                    className="btn btn-default btn-xs" type="button">
                                                    <i className="fa fa-search-plus"></i>
                                                </Link>
                                                <Link
                                                    to={Config.MENUS_ABSOLUTE.HOMEWORK_UPDATE.replace(':id', item.id)}
                                                    className="btn btn-default btn-xs" type="button">
                                                    <i className="fa fa-pencil"></i>
                                                </Link>
                                                <button
                                                    className="btn btn-default btn-xs"
                                                    onClick={
                                                        ()=> {
                                                            if (confirm(Lang.ACTIVITY_LIST.delete_confirm)) {
                                                                self.deleteItem(item.id)
                                                            }
                                                        }
                                                    }
                                                    type="button">
                                                    <i className="fa fa-times"></i>
                                                </button>
                                            </td>

                                        </tr>
                                    }
                                )
                            }
                            </tbody>
                        </table>
                        {
                            data.list.length ? '' : <NoData />
                        }
                        {
                            (data.list.length ? <Pagination
                                onselect={(num)=> {
                                    self.search({
                                        currentPage: num,
                                    });
                                }}

                                page={state.page}
                                onChange={(limit)=> {
                                    self.search({
                                        pageSize: limit
                                    });
                                }}
                            /> : '' )
                        }
                    </Col>
                </Row >
            </Panel>
        )
    }
});
function select(state) {
    return {
        [md5Url.ACTIVITY_FIND]: state.fetchBySubject[md5Url.ACTIVITY_FIND],
        [PAGE_SUBJECT.ACTIVITY]: state.pageBySubject[PAGE_SUBJECT.ACTIVITY],
        [md5Url.ACTIVITY_CATEGORY_FIND]: state.fetchBySubject[md5Url.ACTIVITY_CATEGORY_FIND],
        user: state.user
    }
}
export default connect(select)(Activity)
